/*
 * @Author: gonglf 457423258@qq.com
 * @Date: 2022-06-11 10:58:00
 * @LastEditors: gonglf
 * @LastEditTime: 2022-07-11 10:25:16
 * @FilePath: /distributed-asynchronous-task/utils/reflect.go
 * @Description:
 *
 * Copyright (c) 2022 by gonglf 457423258@qq.com, All Rights Reserved.
 */
package utils

import (
	"encoding/json"
	"reflect"
)

//反射处理

//将参数转化成，方法的参数
/**
 * @description: 将字符串转化成方法的参数
 * @param {reflect.Value} funcValue
 * @param {[]string} funcArgs
 * @return {*}
 */
func GetCallInArgs(funcValue reflect.Value, funcArgs []string) ([]reflect.Value, error) {
	var inArgs = make([]reflect.Value, funcValue.Type().NumIn())
	for i := 0; i < funcValue.Type().NumIn(); i++ {
		if i >= len(funcArgs) {
			break
		}
		inType := funcValue.Type().In(i)
		inValue := reflect.New(inType)
		//获取参数的值
		err := json.Unmarshal([]byte(funcArgs[i]), inValue.Interface())

		if err != nil {
			return inArgs, err
		}
		inArgs[i] = inValue.Elem()
	}
	return inArgs, nil
}

func Arg2Json(v interface{}) (string, error) {
	b, err := json.Marshal(v)
	return string(b), err
}

func Args2JsonSlice(args ...interface{}) ([]string, error) {
	var r = make([]string, len(args))
	for i, v := range args {
		jsonStr, err := Arg2Json(v)
		if err != nil {
			return r, err
		}
		r[i] = jsonStr
	}
	return r, nil
}
